<?php


namespace PKApp\Content\Classes;

use PKFrame\DataHandler\Arrays;
use PKFrame\DataHandler\Numbers;

class MakeHtml extends ContentDetailController
{
    protected $entity_category;

    public function __construct($_entity_category)
    {
        $this->is_makeHtml_category = true;
        $this->entity_category = $_entity_category;
    }

    public function Main()
    {
    }

    public function Category($page_index)
    {
        request()->get([
            'page' => $page_index,
            'siteId' => $this->entity_category['siteId'],
            'catId' => $this->entity_category['id'],
        ]);
        self::$makeHtml_is_mobile = false;
        $html_pc = $this->tplCetegory();
        if ($isOpen_mobile = $this->isOpenMobile()) {
            self::$makeHtml_is_mobile = true;
            $this->getCategoryEntityByNow(true);
            $html_mobile = $this->tplCetegory();
        }
        $set_tpl = $this->entity_category['template'];
        $url = self::UrlPathOfCategory($this->entity_category, $set_tpl, null, true);
        [$path_dir, $path_file] = $this->pathResolve($url, $page_index);
        // 栏目列表的首页
        $is_makeHtml = true;
        if ($this->entity_category['categoryType'] == 'list' && $page_index == 1) {
            // 是否设置关闭了第1页的设置
            $is_makeHtml = empty(Arrays::GetKey('isClosePageByFirst', $set_tpl));
            // 栏目为第一页时
            [$path_once_dir, $path_once_file] = $this->pathResolve($url, $page_index, false);
            $match_str = '(-\[page\]|_\[page\]|/\[page\]|\[page\])';
            $path_once_dir = preg_replace($match_str, '', $path_once_dir);
            $path_once_file = preg_replace($match_str, '', $path_once_file);
            $this->_createhtml($this->diskPathByPc() . $path_once_dir, $path_once_file, $html_pc);
            if ($isOpen_mobile && isset($html_mobile)) {
                $this->_createhtml($this->diskPathByMobile() . $path_once_dir, $path_once_file, $html_mobile);
            }
        }
        if ($is_makeHtml) {
            $this->_createhtml($this->diskPathByPc() . $path_dir, $path_file, $html_pc);
            if ($isOpen_mobile && isset($html_mobile)) {
                $this->_createhtml($this->diskPathByMobile() . $path_dir, $path_file, $html_mobile);
            }
        }
    }

    protected function tplCetegory()
    {
        ob_start();
        $this->getParentIdList();
        $tplFile = '';
        switch ($this->getCategoryEntityByNow()->categoryType) {
            case 'page':
                $this->getDetailByPage();
                $tplFile = $this->getCategoryEntityByNow()->template['pageTpl'];
                break;
            case 'list':
                $this->assign(['nowPage' => max(Numbers::To(request()->get('page')), 1)]);
                $tplFile = $this->getCategoryEntityByNow()->template['categoryTpl'];
                break;
        }
        !empty($tplFile) ? $tplFile = substr($tplFile, 0, strlen($tplFile) - 4) :
            out()->noticeByJson($this->entity_category['name'] . ' ' . language('Category_tplEmpty'));
        self::$makeHtml_is_mobile == false ?: $tplFile .= '_m';
        $this->_fetch($tplFile);
        $html = ob_get_contents();
        ob_end_clean();
        return $html;
    }

    public function Content(array $entity_content, int $page = null)
    {
        $this->is_makeHtml_category = false;
        request()->get([
            'siteId' => $this->entity_category['siteId'],
            'catId' => $this->entity_category['id'],
            'contentId' => $entity_content['id'],
        ]);
        self::$makeHtml_is_mobile = false;
        $html_pc = $this->tplContent($entity_content);
        if ($isOpen_mobile = $this->isOpenMobile()) {
            self::$makeHtml_is_mobile = true;
//            $this->getCategoryEntityByNow(true);
            $html_mobile = $this->tplContent($entity_content);
        }
        $url = self::UrlPathOfContent($this->entity_category, $this->entity_category['template'], $entity_content, null, $page);
        [$path_dir, $path_file] = $this->pathResolve($url);
        $this->_createhtml($this->diskPathByPc() . $path_dir, $path_file, $html_pc);
        if ($isOpen_mobile && isset($html_mobile)) {
            $this->_createhtml($this->diskPathByMobile() . $path_dir, $path_file, $html_mobile);
        }
    }

    protected function tplContent($entity_content)
    {
        ob_start();
        $this->getParentIdList();
        $this->getModelFieldByPower();
        $entity_content = $this->handlerContentData($entity_content);
        $this->assign($entity_content);
        $this->getUpOrNext($entity_content);
        self::$makeHtml_is_mobile == false ?: $this->tpl_content .= '_m';
        $this->_fetch($this->tpl_content);
        $html = ob_get_contents();
        ob_end_clean();
        return $html;
    }

    private function _fetch($template = '', $dir = null)
    {
        is_null($dir) ?: $this->view()->SetTplDir($dir);
        echo $this->view()->TplDisplay($template);
    }

    private function _createhtml($dir, $file, $data)
    {
        fileHelper()->PutContents($dir, $file, $data);
    }

    /**
     * 处理 URL 规则
     * @param string $path
     * @param int|null $pageIndex
     * @param bool $isReplacePage
     * @return array
     */
    protected function pathResolve(string $path, int $pageIndex = null, bool $isReplacePage = true): array
    {
        $path = ltrim($path, '/');
        $dir = $file = '';
        if ($isReplacePage && !is_null($pageIndex)) {
            $path = str_replace('[page]', $pageIndex, $path);
        }
        $files_arr = explode('/', $path);
        while (count($files_arr) > 1) {
            $dir .= array_shift($files_arr) . DS;
        }
        $file = array_shift($files_arr);
        return [$dir, $file];
    }

}
